package app.beit.finportal.interceptor;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import app.beit.finportal.bean.AccountBean;
import app.beit.finportal.utils.constr.SessionConstr;

public class FinPortalInterceptor extends HandlerInterceptorAdapter {

	private final Logger log = Logger.getLogger(this.getClass());
	private final SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSSS");
	
	@Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
		log.info("Interceptor: Pre-handle");

		final String contextPath = request.getContextPath();
		final String requestURI = request.getRequestURI();
		
		final String backdoor = contextPath+"/backend";
		if(requestURI.startsWith(backdoor)){
			this.log.info(requestURI);
			
			int indexOf = requestURI.lastIndexOf("/");
			String path = requestURI.substring(indexOf+1).trim();
			if(path.equalsIgnoreCase("")){
				path = requestURI.substring(0, indexOf);
			}
			final AccountBean user = (AccountBean) request.getSession().getAttribute(SessionConstr.USER);
			if(!path.equalsIgnoreCase("") && !path.equalsIgnoreCase("backend")){
				if(!path.equalsIgnoreCase("login") && !path.equalsIgnoreCase("checkUser")){
					if(user == null){
						response.sendRedirect(contextPath + "/backend");
					}
				}
			}else{
				if(user != null){
					response.sendRedirect(contextPath + "/backend/news");
				}
			}
		}
		
		return true;
	}
	
	@Override
    public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception {
        this.log.info("Request URL::" + request.getRequestURL().toString()
                + " Sent to Handler :: Current Time=" + this.sf.format(new Date(System.currentTimeMillis())));
    }
 
    @Override
    public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception {
        this.log.info("Request URL::" + request.getRequestURL().toString()
                + ":: End Time=" + this.sf.format(new Date(System.currentTimeMillis())));
    }
}
